package com.zl.tesseract.scanner.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.Result;
import com.zl.tesseract.R;
import com.zl.tesseract.scanner.adapter.FcListAdapter;
import com.zl.tesseract.scanner.app.AppConfigs;
import com.zl.tesseract.scanner.app.AuthPreferences;
import com.zl.tesseract.scanner.baiduai.util.GsonUtils;
import com.zl.tesseract.scanner.beans.BrandBean;
import com.zl.tesseract.scanner.beans.CustomBean;
import com.zl.tesseract.scanner.beans.EnterBean;
import com.zl.tesseract.scanner.beans.EnterCommitBean;
import com.zl.tesseract.scanner.beans.ShelvesBean;
import com.zl.tesseract.scanner.camera.CameraManager;
import com.zl.tesseract.scanner.decode.CaptureEnterActivityHandler;
import com.zl.tesseract.scanner.decode.DecodeManager;
import com.zl.tesseract.scanner.decode.InactivityTimer;
import com.zl.tesseract.scanner.greendao.services.EnterBeanService;
import com.zl.tesseract.scanner.manager.BeepManager;
import com.zl.tesseract.scanner.retrofit.Api;
import com.zl.tesseract.scanner.retrofit.HttpUtil;
import com.zl.tesseract.scanner.retrofit.NetCallBack;
import com.zl.tesseract.scanner.utils.DataUtils;
import com.zl.tesseract.scanner.view.ImageDialog;
import com.zl.tesseract.scanner.view.ScannerFinderView;
import com.zl.tesseract.scanner.view.SwipeItemLayout;
import com.zl.tesseract.scanner.views.pickerview.PickerViewUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 代收到付。
 */
public class EnterActivity extends Activity implements Callback {

    private final String TAG = EnterActivity.class.getSimpleName();
    private Context mContext;

    @BindView(R.id.iv_flash)
    ImageView iv_flash;

    @BindView(R.id.qr_code_view_stub)
    ViewStub qr_code_view_stub;
    @BindView(R.id.qr_code_view_finder)
    ScannerFinderView qr_code_view_finder;
    @BindView(R.id.qr_code_view_background)
    View qr_code_view_background;

    @BindView(R.id.btn_take_photo)
    Button btn_take_photo;

    @BindView(R.id.tv_select_brand)
    TextView tv_select_brand;

    @BindView(R.id.edt_waybill_number)
    EditText edt_waybill_number;
    @BindView(R.id.iv_scan_waybill_number)
    ImageView iv_scan_waybill_number;

    @BindView(R.id.edt_phone)
    EditText edt_phone;
    @BindView(R.id.iv_scan_phone)
    ImageView iv_scan_phone;

    @BindView(R.id.tv_select_shelves)
    TextView tv_select_shelves;
    @BindView(R.id.tv_select_custom)
    TextView tv_select_custom;

    @BindView(R.id.recyclerView_fc)
    RecyclerView recyclerView_fc;

    @BindView(R.id.btn_save_and_exit)
    Button btn_save_and_exit;
    @BindView(R.id.btn_confirm_move)
    Button btn_confirm_move;


    private CaptureEnterActivityHandler mCaptureActivityHandler;
    private boolean mHasSurface;
    private InactivityTimer mInactivityTimer;
    private SurfaceView mSurfaceView;
    private DecodeManager mDecodeManager = new DecodeManager();

    private BeepManager beepManager;

    private ProgressDialog progressDialog;
    private Bitmap bmp;

    private boolean isQRcode = true;// true-扫条形码，false-扫手机号

    private List<BrandBean> brandBeans;// 品牌
    private int brandSelectPosition = -1;
    private List<ShelvesBean> shelvesBeans;// 货架
    private int shelvesSelectPosition = -1;
    private List<CustomBean> customBeans;// 快递类型
    private int customSelectPosition = -1;

    private List<EnterBean> enterBeanList;
    private FcListAdapter fcListAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter);
        ButterKnife.bind(this);
        mContext = this;

        initView();
        initData();

        getBrands();
    }

    private void initView() {
        mHasSurface = false;
        // 默认不扫描手机号
        btn_take_photo.setVisibility(View.VISIBLE);
    }

    private void initData() {
        mInactivityTimer = new InactivityTimer(this);

        beepManager = new BeepManager(this);
        beepManager.setPlayBeep(true);
        beepManager.setVibrate(true);


        enterBeanList = EnterBeanService.findAll();
        if (enterBeanList == null) {
            enterBeanList = new ArrayList<>();
        }
        fcListAdapter = new FcListAdapter(mContext, enterBeanList);
        recyclerView_fc.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView_fc.setAdapter(fcListAdapter);
        recyclerView_fc.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(mContext));
    }

    @OnClick({R.id.iv_titlebar_left, R.id.iv_flash, R.id.tv_confirm
            , R.id.btn_take_photo
            , R.id.iv_scan_waybill_number, R.id.iv_scan_phone
            , R.id.tv_select_brand, R.id.tv_select_shelves, R.id.tv_select_custom
            , R.id.btn_save_and_exit, R.id.btn_confirm_move})
    public void onViewClick(View view) {
        EnterBean enterBean;
        switch (view.getId()) {
            case R.id.iv_titlebar_left:
                Log.d(TAG, "点击iv_titlebar_left");
                finish();
                break;
            case R.id.iv_flash:
                if (CameraManager.get().getFlashMode()) {
                    // 开启了闪光灯，应该关闭
                    iv_flash.setImageResource(R.drawable.flash_off);
                    CameraManager.get().setFlashLight(false);
                } else {
                    iv_flash.setImageResource(R.drawable.flash_on);
                    CameraManager.get().setFlashLight(true);
                }
                break;
            case R.id.tv_confirm:
                // 确认
                enterBean = getBeanFromForm();
                if (enterBean != null) {
                    fcListAdapter.append(enterBean);
                }
                break;
            case R.id.btn_take_photo:
                btn_take_photo.setEnabled(false);
                buildProgressDialog();
                break;
            case R.id.iv_scan_waybill_number:
                qr_code_view_finder.setScanCodeMode(mContext);
                isQRcode = true;
                break;
            case R.id.iv_scan_phone:
                qr_code_view_finder.setScanPhoneMode(mContext);
                isQRcode = false;
                break;
            case R.id.btn_save_and_exit:
                // 保存退出
                enterBean = getBeanFromForm();
                EnterBeanService.deleteAll();
                EnterBeanService.saveOne(enterBean);
                Log.d(TAG, "点击btn_save_and_exit");
                finish();
                break;
            case R.id.btn_confirm_move:
                // 确认移库
                enterBean = getBeanFromForm();
                if (enterBean != null) {
                    fcListAdapter.append(enterBean);
                }
                break;
            case R.id.tv_select_brand:
                if (brandBeans == null || brandBeans.size() == 0) {
                    return;
                }
                final ArrayList<String> brandNameList = new ArrayList<>();
                for (BrandBean brandBean : brandBeans) {
                    brandNameList.add(brandBean.getNama());
                }
                PickerViewUtil.alertBottomWheelOption(mContext, brandNameList, brandSelectPosition, R.string.select_brand,
                        new PickerViewUtil.OnWheelViewClick() {
                            @Override
                            public void onClick(View view, int postion) {
                                brandSelectPosition = postion;
                                tv_select_brand.setText(brandNameList.get(postion));
                            }
                        }
                );
                break;
            case R.id.tv_select_shelves:
                // 确认移库
                if (shelvesBeans == null || shelvesBeans.size() == 0) {
                    return;
                }
                final ArrayList<String> shelvesNameList = new ArrayList<>();
                for (ShelvesBean shelvesBean : shelvesBeans) {
                    shelvesNameList.add(shelvesBean.getSname());
                }
                PickerViewUtil.alertBottomWheelOption(mContext, shelvesNameList, shelvesSelectPosition, R.string.select_shelves,
                        new PickerViewUtil.OnWheelViewClick() {
                            @Override
                            public void onClick(View view, int postion) {
                                shelvesSelectPosition = postion;
                                tv_select_shelves.setText(shelvesNameList.get(postion));
                            }
                        }
                );
                break;
            case R.id.tv_select_custom:
                // 确认移库
                if (customBeans == null || customBeans.size() == 0) {
                    return;
                }
                final ArrayList<String> customNameList = new ArrayList<>();
                for (CustomBean customBean : customBeans) {
                    customNameList.add(customBean.getType_name());
                }
                PickerViewUtil.alertBottomWheelOption(mContext, customNameList, customSelectPosition, R.string.select_custom,
                        new PickerViewUtil.OnWheelViewClick() {
                            @Override
                            public void onClick(View view, int postion) {
                                customSelectPosition = postion;
                                tv_select_custom.setText(customNameList.get(postion));
                            }
                        }
                );
                break;
            default:
                break;
        }
    }

    private EnterBean getBeanFromForm() {
        if (TextUtils.isEmpty(edt_waybill_number.getText().toString())) {
            Toast.makeText(mContext, "运单号不能为空", Toast.LENGTH_LONG).show();
            return null;
        }
        if (TextUtils.isEmpty(edt_phone.getText().toString())) {
            Toast.makeText(mContext, "手机号不能为空", Toast.LENGTH_LONG).show();
            return null;
        }
        EnterBean enterBean = new EnterBean();
        if (brandBeans == null || brandSelectPosition < 0) {
            Toast.makeText(mContext, "请选择快递品牌", Toast.LENGTH_LONG).show();
//            return null;
        }
//        enterBean.setLogistics_id(brandBeans.get(brandSelectPosition).getId());//品牌id
//        enterBean.setLogistics_name(brandBeans.get(brandSelectPosition).getNama());//品牌名称
        enterBean.setOrder_id(edt_waybill_number.getText().toString());//快递单号
        enterBean.setPhone(edt_phone.getText().toString());//单号对应手机号
        if (shelvesBeans == null || shelvesSelectPosition < 0) {
            Toast.makeText(mContext, "请选择货架", Toast.LENGTH_LONG).show();
//            return null;
        }
//        enterBean.setShelf_number(shelvesBeans.get(shelvesSelectPosition).getId() + "");//货架号
        if (customBeans == null || customSelectPosition < 0) {
            Toast.makeText(mContext, "请选择快递类型", Toast.LENGTH_LONG).show();
//            return null;
        }
//        enterBean.setExpress_delivery_type(customBeans.get(customSelectPosition).getId() + "");//快件类型
        return enterBean;
    }

    public Rect getCropRect() {
        return qr_code_view_finder.getRect();
    }

    /**
     * 返回是否是扫条形码格式
     *
     * @return boolean
     */
    public boolean isQRCode() {
        return isQRcode;
    }

    @Override
    protected void onResume() {
        super.onResume();
        CameraManager.init();
        initCamera();

        beepManager.updatePrefs();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持屏幕常亮
    }

    private void initCamera() {
        if (null == mSurfaceView) {
            qr_code_view_stub.setLayoutResource(R.layout.layout_surface_view);
            mSurfaceView = (SurfaceView) qr_code_view_stub.inflate();
        }
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        if (mHasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            // 防止sdk8的设备初始化预览异常(可去除，本项目最小16)
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "执行onPause()方法");
        if (mCaptureActivityHandler != null) {
            try {
                mCaptureActivityHandler.quitSynchronously();
                mCaptureActivityHandler = null;
                if (null != mSurfaceView && !mHasSurface) {
                    mSurfaceView.getHolder().removeCallback(this);
                }
                CameraManager.get().closeDriver();
            } catch (Exception e) {
                // 关闭摄像头失败的情况下,最好退出该Activity,否则下次初始化的时候会显示摄像头已占用.
                Log.d(TAG, "关闭摄像头失败");
                finish();
            }
        }

        beepManager.close();

        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 取消屏幕常亮

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (null != mInactivityTimer) {
            mInactivityTimer.shutdown();
        }
        Log.d(TAG, "执行onDestroy()方法");
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     */
    public void handleDecode(Result result) {
        mInactivityTimer.onActivity();

        beepManager.playBeepSoundAndVibrate();

        if (null == result) {
            mDecodeManager.showCouldNotReadQrCodeFromScanner(this, new DecodeManager.OnRefreshCameraListener() {
                @Override
                public void refresh() {
                    restartPreview();
                }
            });
        } else {
            handleResult(result);
        }
    }

    public void handleDecode(String phoneResult) {
        mInactivityTimer.onActivity();

        beepManager.playBeepSoundAndVibrate();

        if (TextUtils.isEmpty(phoneResult)) {
            mDecodeManager.showCouldNotReadQrCodeFromScanner(this, new DecodeManager.OnRefreshCameraListener() {
                @Override
                public void refresh() {
                    restartPreview();
                }
            });
        } else {
            edt_phone.setText(phoneResult);
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            if (!CameraManager.get().openDriver(surfaceHolder)) {
                return;
            }
        } catch (IOException e) {
            Log.d(TAG, "initCamera-相机不存在");
            // 基本不会出现相机不存在的情况
            Toast.makeText(this, getString(R.string.camera_not_found), Toast.LENGTH_SHORT).show();
            finish();
            return;
        } catch (RuntimeException re) {
            re.printStackTrace();
            return;
        }
        qr_code_view_finder.setVisibility(View.VISIBLE);
        qr_code_view_background.setVisibility(View.GONE);
        if (mCaptureActivityHandler == null) {
            mCaptureActivityHandler = new CaptureEnterActivityHandler(this);
        }
    }

    public void restartPreview() {
        if (null != mCaptureActivityHandler) {
            try {
                mCaptureActivityHandler.restartPreviewAndDecode();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!mHasSurface) {
            mHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mHasSurface = false;
    }

    public Handler getCaptureActivityHandler() {
        return mCaptureActivityHandler;
    }

    /**
     * 获取到扫条形码的结果，处理结果
     *
     * @param result Result
     */
    private void handleResult(Result result) {
        if (TextUtils.isEmpty(result.getText())) {
            mDecodeManager.showCouldNotReadQrCodeFromScanner(this, new DecodeManager.OnRefreshCameraListener() {
                @Override
                public void refresh() {
                    restartPreview();
                }
            });
        } else {
            if (isQRcode) {
                qrSucceed(result.getText());
            } else {
                phoneSucceed(result.getText(), result.getBitmap());
            }
        }
    }

    /**
     * 获取到条形码成功，弹窗显示
     *
     * @param result
     */
    private void qrSucceed(final String result) {
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.notification)
                .setMessage(result)
                .setPositiveButton(R.string.positive_button_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        restartPreview();

                        edt_waybill_number.setText(result);
                    }
                })
                .show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                restartPreview();
            }
        });
    }

    private void phoneSucceed(String result, Bitmap bitmap) {
        ImageDialog dialog = new ImageDialog(this);
        dialog.addBitmap(bitmap);
        dialog.addTitle(TextUtils.isEmpty(result) ? "未识别到手机号码" : result);
        dialog.show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                restartPreview();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            btn_take_photo.setEnabled(true);
            cancelProgressDialog();
            switch (msg.what) {
                case 0:
                    phoneSucceed((String) msg.obj, bmp);
                    break;
                case 1:
                    Toast.makeText(EnterActivity.this, "无法识别", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 加载dialog
     */
    public void buildProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        progressDialog.setMessage("识别中...");
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    /**
     * 取消加载dialog
     */
    public void cancelProgressDialog() {
        if (progressDialog != null) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    }

    /**
     * 获取快递品牌
     */
    private void getBrands() {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("token", AppConfigs.APP_TOKEN);
        HttpUtil.getInstance().getRequestData(Api.GET_SHOP_GET_LOGISTICS, map, new NetCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String listStr = jsonObject.optString("data");
                    brandBeans = DataUtils.getGson().fromJson(listStr, new TypeToken<List<BrandBean>>() {
                    }.getType());
                    if (brandBeans != null && brandBeans.size() > 0) {
                        tv_select_brand.setText(brandBeans.get(0).getNama());
                    }
                    getShelves();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String message, String data) {
                Toast.makeText(mContext, "获取快递品牌失败", Toast.LENGTH_SHORT).show();
                getShelves();
            }
        });
    }

    /**
     * 获取货架号
     */
    private void getShelves() {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("token", "MTU2MTI3OTk4NzE2MzM4Ng");
        HttpUtil.getInstance().getRequestData(Api.GET_GETSHELEVESFROMTOKEN, map, new NetCallBack() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    shelvesBeans = DataUtils.getGson().fromJson(jsonObject.getString("data"), new TypeToken<List<ShelvesBean>>() {
                    }.getType());
//                    if(shelvesBeans != null && shelvesBeans.size() > 0){
//                        tv_select_shelves.setText(shelvesBeans.get(0).getSname());
//                    }
                    getShelvesCustomList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String message, String data) {
                Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                getShelvesCustomList();
            }
        });
    }

    /**
     * 获取快递类型
     */
    private void getShelvesCustomList() {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("token", "MTU2MTI3OTk4NzE2MzM4Ng");
        HttpUtil.getInstance().getRequestData(Api.GET_SHOP_GET_SHELVES_CUSTOM_LIST, map, new NetCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    customBeans = DataUtils.getGson().fromJson(jsonObject.getString("data"), new TypeToken<List<CustomBean>>() {
                    }.getType());
//                    if(customBeans != null && customBeans.size() > 0){
//                        tv_select_custom.setText(customBeans.get(0).getType_name());
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String message, String data) {
                Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 提交
     */
    private void doCommit(final String methodName, final String companyid) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        EnterCommitBean enterCommitBean = new EnterCommitBean();
        enterCommitBean.setToken(AuthPreferences.getToken());
        enterCommitBean.setData(enterBeanList);
        map.put("enterData", GsonUtils.toJson(null));
        HttpUtil.getInstance().putRequestData(Api.PUT_SHOPENTER, map, new NetCallBack() {
            @Override
            public void onSuccess(String jsonObjectStr) {
//                if (methodName.equals(METHOD_NAME_GETDEVICESTATISTICS)) {
//                    getDeviceStatistics(companyid);
//                }
            }

            @Override
            public void onFailure(int code, String message, String data) {
//                if (methodName.equals(METHOD_NAME_GETDEVICESTATISTICS)) {
//                    dismissProgressDialog();
//                    ViewUtil.showCenterToast(getApplicationContext(), "获取机群状态失败");
//                }
            }
        });
    }

}